package com.zb.mail;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

//普通只带文本的邮件
public class SimpleMail {

    //授权码：wtacdribubspbdhh
    public static void main(String[] args) throws Exception {
        Properties properties = new Properties();
        properties.setProperty("mail.host", "smtp.qq.com");
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.smtp.auth", "true");

        //以下设置为QQ邮箱必须,设置ssl加密
        /*MailSSLSocketFactory mailSSLSocketFactory = new MailSSLSocketFactory();
        mailSSLSocketFactory.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", mailSSLSocketFactory);*/

        //使用JavaMail发送邮件的5个步骤
        //1、创建定义整个应用程序所需的环境信息的Session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("594507903@qq.com", "wtacdribubspbdhh");
            }
        });
        //开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
        session.setDebug(true);

        //2、通过session得到transport对象
        Transport transport = session.getTransport();

        //3、使用邮箱的用户名和授权码连上邮件服务器
        transport.connect();
//        transport.connect("smtp.qq.com", "594507903@qq.com", "wtacdribubspbdhh");

        //4、创建邮件
        MimeMessage message = new MimeMessage(session);
        //指明发件人
        message.setFrom(new InternetAddress("594507903@qq.com"));
        //指明收件人
        message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress("594507903@qq.com"));
        //主题
        message.setSubject("主题");
        //内容
        message.setContent("<h1 style='color:red'>你好呀！</h1>", "text/html;charset=UTF-8");
        message.saveChanges();//保存设置

        //5、发送邮件
        transport.sendMessage(message, message.getAllRecipients());

        //6、关闭连接
        transport.close();


    }
}
